package com.coolxi.upload;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Random;

/**
 * Created by Eoly on 2017/6/13.
 */
public class WebFileUpload implements Upload {

    private MultipartFile file;
    private String fileName;
    private String originalFilename;
    private String extensionName;
    private String realPath;
    private String uploadFileName;

    public WebFileUpload(MultipartFile file, HttpServletRequest request, String path) {
        this.file = file;
        if (!file.isEmpty()){
            this.originalFilename = file.getOriginalFilename();
            this.fileName = file.getName();
            this.realPath = request.getSession().getServletContext().getRealPath(path);
            this.extensionName = this.originalFilename.split("\\.", 2)[1];
            this.uploadFileName = this.fileName;
        }
    }

    public WebFileUpload(MultipartFile file, HttpServletRequest request, String path, boolean isRandomName) {
        this(file, request, path);
        if (isRandomName){
            this.uploadFileName = getRandomName() + "." + this.extensionName;
        }
    }

    @Override
    public String getFileName() {
        return this.fileName;
    }

    @Override
    public String getOriginalFilename() {
        return this.originalFilename;
    }

    @Override
    public String getExtensionName() {
        return this.extensionName;
    }

    @Override
    public void upload() throws IOException {
        if (!this.file.isEmpty()){
            File file = new File(getRealPath() + "/" + getUploadFileName());
            FileUtils.copyInputStreamToFile(getFile().getInputStream(), file);
        }
    }

    @Override
    public String getRealPath() {
        return this.realPath;
    }

    @Override
    public String getUploadFileName() {
        return this.uploadFileName;
    }

    public MultipartFile getFile() {
        return file;
    }

    public void setFile(MultipartFile file) {
        this.file = file;
    }

    private String getRandomName() {
        //以当前时间加随机数命名上传文件
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
        String date = sdf.format(new java.util.Date());

        //设置图片名为当前时间加随机数
        return date + new Random().nextInt() + "." + extensionName;
    }
}
